<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Reserve;
use App\Models\User;

class ReserveController extends Controller
{
	private $uid;
	private $reserve;
	private $user;

	public function __construct(Request $request)
    {
		$this->middleware(function ($request, $next) {
			$this->uid = session('uid');
			return $next($request);
		});

		$this->reserve = new Reserve;
		$this->user = new User;
    }

    // Dashboard
    public function dashboard(Request $request)
    {
    	$user = $this->user->find($this->uid);
    	$data = $user->reserve->toArray();
    	return view('dashboard', ['title' => 'Dashboard', 'data' => $data]);
    }

    // ReservePage
    public function reserve(Request $request)
    {
    	$carnivalDays = env('CARNIVAL_DAYS');
    	$currentDay = env('CURRENT_DAY');
    	$data = [
			'title'        => 'New Reservation',
			'carnivalDays' => $carnivalDays,
			'currentDay'   => $currentDay
    	];
    	return view('reserve', $data);
    }

	// 添加预定
	public function add_reserve(Request $request)
	{
		try {
			$data = $request -> only(['date'], 'post');
			if (!$data['date']) {
				return $this->ReturnError('Please select an appointment time.');
			}
			$reserve = $this->reserve;
			// 获取该用户5天活动内的预约数量
			$reserveNum = $reserve->getReserveNum($this->uid);
			if ($reserveNum >= 3) {
				return $this->ReturnError('Up to 3 appointments can be made within 5 days.');
			}
			// 获取该用户当天是否存在预约
			$reserveExist = $reserve->getReserveExist($this->uid, $data['date']);
			if ($reserveExist) {
				return $this->ReturnError('There can only be 1 appointment per day.');
			}
			// 获取整个活动（5天内）的总预订数量
			$reserveCount = $reserve->getReserveCount();
			if ($reserveCount >= 10) {
				return $this->ReturnError('No more locations.');
			}

			// 保存数据
			$reserve->reserved_day = $data['date'];
			$reserve->invitation_code = $this->createCode();
			$reserve->create_date = date('Ymd', time());
			$reserve->create_time = time();
			$reserve->uid = session('uid');
			$reserve->user_name = session('username');
			$reserve->save();

			return $this->ReturnSuccess('Appointment successful.');
		} catch(\Exception $e) {
			// dd($e->getMessage());
			return $this->ReturnError('system error');
		}
	}

	// 取消预约
	public function cancel(Request $request)
	{
		try {
			$id = $request->id;
			if (!$id) {
				return ReturnError('Required parameters cannot be blank.');
			}
			$reserve = $this->reserve->find($id);
			$reserve->delete();
			return $this->ReturnSuccess('Cancel the success.');
		} catch(\Exception $e) {
			return $this->ReturnError('system error');
		}
	}

	// 生成邀请码
	private function createCode($length = 6)
	{
		$str = '';
     	for($i = 0; $i < $length; $i++){
         	$rand = "qwertyuioplkjhgfdsazxcvbnm";
         	$str .= $rand[mt_rand(0,25)];
        }
     	return $str;
	}
}
